﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WiseLinkWPF.Windows.Controls.GridView;
using WiseLinkWPF.Windows.Controls;
using CCF20Model;
using System.Collections;
using System.Data;
namespace CCF20
{
    /// <summary>
    /// Interaction logic for VehicleMessage.xaml
    /// </summary>
    public partial class VehicleMessage : UserControl
    {
        VehicleModel vehicleModel;
        FaultModel faultModel;
        int currentVehicleID;
        
        public static readonly DependencyProperty FilterNameProperty = DependencyProperty.Register("FilterName", typeof(string), typeof(VehicleMessage), null);
        public string FilterName
        {
            get
            {
                return (string)GetValue(FilterNameProperty);
            }

            set
            {
                SetValue(FilterNameProperty, value);
            }
        }
        public VehicleMessage()
        {
            InitializeComponent();
            vehicleModel = new VehicleModel();
            faultModel = new FaultModel();
            
            
            
        }

        //private void RadmaintenanceCount_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        //{
        //    var row = this.radGridTroubleVehicle.ItemContainerGenerator.ContainerFromItem(this.radGridTroubleVehicle.SelectedItem) as GridViewRow;
        //    if (row != null)
        //    {
        //        if (row.DetailsVisibility == Visibility.Visible)
        //        {
        //            row.DetailsVisibility = Visibility.Collapsed;
        //        }
        //        else 
        //        {
        //            row.DetailsVisibility = Visibility.Visible;
        //        }
        //    }

        //}

        private void VehicleMessageToolBar_Click(object sender, RoutedEventArgs e)
        {
            string strAction = ((Button)sender).Name;
            switch (strAction)
            {
                case "Refresh":
                    LoadData();
            
                    this.Dispatcher.BeginInvoke(new Action(() => this.gridVehicle.Rebind()));
                    break;
                case "ClearCode":
                    int codeType = 0;
                    VehicleData vd = (VehicleData)this.gridVehicle.CurrentItem;
                    string  selectedItem = ((RadComboBoxItem)this.comboClear.SelectedValue).Content.ToString();
                    switch (selectedItem)
                    {
                        case "发动机":
                            codeType = 257;
                            break;

                        case "自动变速箱":
                            codeType = 513;
                            break;
                        case "abs制动":
                            codeType = 769;
                            break;

                        case "安全气囊":
                            codeType = 5377;
                            break;

                    }
                    MessageBoxResult confirmResult = MessageBox.Show(
                         string.Format("请确认对车辆\"{0}\"进行\"{1}\"清码!\r\n 请注意： 1.远程清码必需在驻车状态下进行，确保人车安全。\r\n\t 2. 在清码过程中，收音机信号会有瞬时中断。",
                                            vd.MyDevice.IDCSimNumber,
                                            selectedItem), "CCF2.0", MessageBoxButton.OKCancel);

                            if (confirmResult != MessageBoxResult.OK)
                            {
                                return;
                            }
                            
                    CCFZIC ccfZIC = new CCFZIC();
                    this.Dispatcher.BeginInvoke(new Action(() =>
                        {

                            MessageBox.Show(string.Format("清码完成，返回代码为 {0}", 
                                                ccfZIC.ClearCode(vd.MyDevice.IDCSimNumber, codeType)),
                                                "CCF2.0",
                                                MessageBoxButton.OK);
                            //if (codeType == 0)
                            //{
                            //    MessageBox.Show("清码成功", "CCF2.0", MessageBoxButton.OKCancel);
                            //}
                            //else
                            //{
                            //    MessageBox.Show(string.Format("清码失败，返回错误码为 {0}", codeType), "CCF2.0", MessageBoxButton.OKCancel);
                            //}
                        }));
                    break;
            }
        }

        private void LoadData()
        {
            IList<VehicleData> mySource = vehicleModel.GetRegisteredVehicle().ToList();
            this.gridVehicle.ItemsSource = mySource.Where(v => v.MyVehicle.UnConfirmedFaultCount > 0
                                                       || v.MyVehicle.UrgentCount > 0
                                                       || v.MyVehicle.MaintenanceCount > 0);
        }
        
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            LoadData();
        }

        private void gridVehicle_SelectionChanged(object sender, SelectionChangeEventArgs e)
        {
            if (e.AddedItems.FirstOrDefault() != null)
            {
                this.gridVehicle.CurrentItem = e.AddedItems.First();
                VehicleData vd = (VehicleData)this.gridVehicle.CurrentItem;
                this.gridFault.ItemsSource = vehicleModel.GetUnconfirmedFaultByVehicle(vd.MyVehicle.VehicleID);
                this.gridMaintenance.ItemsSource = vehicleModel.GetVehicleMaintenanceRequestByVehicle(vd.MyVehicle.VehicleID,true);
                
                
            }
            else
            {
                this.gridFault.ItemsSource = null;
                this.gridMaintenance.ItemsSource = null;
                
                
            }
            this.Dispatcher.BeginInvoke(new Action(() => this.gridFault.Rebind()));
            this.Dispatcher.BeginInvoke(new Action(() => this.gridMaintenance.Rebind()));
            
         
        }

        private void RadMenuItem_Click(object sender, WiseLinkWPF.Windows.RadRoutedEventArgs e)
        {
            GridViewRow row = ((ContextMenu)sender).PlacementTarget as GridViewRow;
            if (row != null)
            {
                row.IsSelected = true;
            }
            string temp = row.Cells[0].Content.ToString();
        }

        private void RadContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            RadContextMenu menu = (RadContextMenu) sender;
            GridViewRow row = menu.GetClickedElement<GridViewRow>();

            if (row != null)
            {
                row.IsSelected = row.IsCurrent = true;
                
            }
            else
            {
                menu.IsOpen = false;
            }
        }
        

        private void RadContextMenu_ItemClick(object sender, WiseLinkWPF.Windows.RadRoutedEventArgs e)
        {
            RadContextMenu menu = (RadContextMenu)sender;
            RadMenuItem clickedItem = e.OriginalSource as RadMenuItem;
            GridViewRow row = menu.GetClickedElement<GridViewRow>();
            
            Fault currentFault =  row.Item as Fault;
            if (clickedItem != null && row != null)
            {
                string header = Convert.ToString(clickedItem.Header);

                switch (header)
                {
                    case "确认":
                        faultModel.ConfirmTroubleCode(currentFault);
                        ((IList)this.gridFault.ItemsSource).Remove(row.DataContext);
                        break;
                    case "修改":
                        this.gridFault.BeginEdit();
                        break;
                    case "排除":
                        faultModel.AddSkipTroubleCode(currentFault);
                        ((IList)this.gridFault.ItemsSource).Remove(row.DataContext);
                        //((ObservableCollection<Fault>)this.gridFault.ItemsSource).Remove((Fault)row.DataContext);
                        //this.gridFault.Items.Remove((Fault)row.DataContext);
                        break;
                    case "直通车":
                        faultModel.AddDirectTroubleCode(currentFault);
                        ((IList)this.gridFault.ItemsSource).Remove(row.DataContext);
                        break;
                    default:
                        break;
                }
            }
        }

        private void gridFault_CellValidating(object sender, GridViewCellValidatingEventArgs e)
        {
            // if there is no change of the value, no need to validate.
            if (e.NewValue == e.OldValue)
                return;
            GridViewCell cell = e.Cell;

            GridViewRow row = this.gridFault.ItemContainerGenerator.ContainerFromItem(this.gridFault.SelectedItem) as GridViewRow;
            Fault currentFault = (Fault)row.DataContext;
            string newValue = e.NewValue as string;
            VehicleData vd = (VehicleData)this.gridVehicle.CurrentItem;

            switch (cell.Column.UniqueName)
            {
                case "CodeDescription":
                    faultModel.CustomizeCodeDescription(vd.MyVehicle.VehicleID, newValue,currentFault);
                    break;
                //case "Priority":
                //    int temp;

                //    try
                //    {
                //        temp = Convert.ToInt16(newValue);
                //        faultModel.CustomizeCodePriority(vd.MyVehicle.VehicleID, temp, currentFault);
                //    }
                //    catch (Exception ex)
                //    {
                //        temp = 0;
                //    }
                //    break;
                default:
                    break;
            }
            
        }

       
        private void gridFault_RowEditEnded(object sender, GridViewRowEditEndedEventArgs e)
        {
            if ((e.EditAction == GridViewEditAction.Commit)||
                (e.EditOperationType == GridViewEditOperationType.Edit))
            {
                vehicleModel.Update();
            }

            
        }
        
    }
}
